import getConfig from '../app'
const app = getApp()
export default function createRequest (option) {
  return new Promise ((resolve)=>{
    //先判断登录还是未登录
    const token = wx.getStorageSync('token');
    if ( option.needLogin !== false && !token ) {
      wx.showToast({
        title: '请先登录',
        icon:'none',
      })
      //如果未登录就跳转登陆页面
      setTimeout(()=>{
        wx.redirectTo({
          url: '/pages/login/index',
        })
      },1500);
      //终止向下执行
      return
    }
    //构造根地址
    const baseUrl = app.getConfig("baseUrl")
    // const baseUrl='http://localhost:3000';
    const url = `${baseUrl}${option.url}`;
    const header = {
      token
    }
    
    //在请求数据数据库的时候显示正在加载
    //showloading 要搭配 hidloading
    let showLoading = false
    if(option.loading !== false){
      showLoading = true
      wx.showLoading({
        title: '正在加载...',
        mask: true
      })
    }

    //请求数据库
    wx.request({
      url,
      method: option.method || 'GET',
      timeout: option.timeout || 20000,
      header,
      data: option.data || {},
      success(res) {
      res = res.data
      switch (res.code) {
        case 0:
          //登录成功
          return resolve(res);
        case -1:
          //登陆异常
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
          break;
        case 403:
          //丢失cookie 需要重新登陆
          wx.showToast({
            title: '登录失效，请重新登录！',
            icon:'none'
          })
          setTimeout(()=>{
            wx.redirectTo({
              url: '/pages/login/index',
            })
          },1500)
          break;
          default:
            wx.showToast({
              title: '服务器开小差啦！',
              icon:'none'
            })
            break;
      }
      },
      fail(){
        wx.showToast({
          title: '服务器开小差啦！',
          icon:'none'
        })
      },
      complete(){
        //完成之后要把loading隐藏
        if(showLoading){
         wx.hideLoading()
        }
      }
    })


  })
}